var express = require('express');
var router = express.Router();
var EventProxy = require('eventproxy');
var util = require('util');

var logger = require("../models/logger")
var Feedback = require("../models/Feedback");
var resultJson = require("../result-json");
var Utils = require("../utils");
var Consts = require("../consts");
var User = require("../models/User");

router.post('/', function(req, res) {
    res.send('respond with a resource');
});

/**
 * 根据id查询问题反馈的详情
 */
router.post("/detail", function(req, res) {
    var feedback = req.body;
    Feedback.findById(feedback._id, function(err, feedback) {
        if (err ) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        if(!feedback)
            return res.send(resultJson(0,{}));
        var feedback = JSON.parse(JSON.stringify(feedback));
        User.findOne({
            "_id": feedback.from
        }, function(err, user) {
            if (err || !user)
                return res.send(resultJson(3));

            feedback.user = user;
            res.send(resultJson(0, feedback));
        });
    });
});

//增加新问题
router.post('/upsert', function(req, res) {
    var feedback = req.body;
    if (feedback._id) {
        feedback.aDate = new Date();
        Feedback.update({
            _id: feedback._id
        }, {
            $set: feedback
        }).exec(function(err) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            res.send(resultJson(0));
        });
    } else {
        feedback.create = new Date();
        feedback.from = feedback._user._id;
        new Feedback(feedback).save(function(err, feedback) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            res.send(resultJson(0, feedback));
        });
    }
});

//列出所有feedback，如果带id参数，那么列出该人下所有问题
router.post('/list', function(req, res) {
    var feedback = req.body;
    var proxy = new EventProxy();
    proxy.all("results", "count", function(results, count) {
        res.send(resultJson(0, {
            results: results,
            count: count
        }))
    })
    var start = feedback.start || 0;
    var count = feedback.count || Consts.MAX;
    var option = {};
    if(feedback.from)
        option.from = feedback.from;
    Feedback.find(option).skip(start).limit(count).sort({
        create: -1
    }).exec(function(err, feedbacks) {
        console.log(feedbacks)
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        var feedbacks = JSON.parse(JSON.stringify(feedbacks));
        var index = 0;
        fromName(res, index, feedbacks, proxy);
    });
    Feedback.find(option).count(function(err, num) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        proxy.emit("count", num);
    });
});

function fromName(res, index, feedbacks, proxy) {
    if (index == feedbacks.length || feedbacks.length == 0) {
        proxy.emit("results", feedbacks);
    } else {
        User.findOne({
            "_id": feedbacks[index].from
        }, function(err, user) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            if (!user)
                user = {};

            feedbacks[index].fromName = user.name;
            index++;
            fromName(res, index, feedbacks, proxy);
        });
    }
};

//删除
router.post('/remove', function(req, res) {
    var feedback = req.body;
    Feedback.remove({
        _id: feedback._id
    }, function(err) {
        if (err) {
            logger.error(err);
            res.send(resultJson(2));
        } else
            res.send(resultJson(0));
    });
});

module.exports = router;